package guyubao.com.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.function.Consumer;


public interface BaseDataUtils {

    default <V> V asViewObject(Class<V> clazz, Consumer<V> consumer){
        V v = this.asViewObject(clazz);
        consumer.accept(v);
        return v;
    }
    default <V> V asViewObject(Class<V> clazz){
        try{
            // 获取传进所有字段
            Field[] declaredFields = clazz.getDeclaredFields();
            // 获取无参构造函数
            Constructor<V> constructor = clazz.getConstructor();
            // 指定类型构实例出来
            V v = constructor.newInstance();
            // 拷贝
            for (Field declaredField : declaredFields) {
                convert(declaredField,v);
            }
            return v;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    // 拷贝字段
    default void convert(Field field, Object vo){
        try {
            // 通过外面给的字段名称获得当前类型字段的值
            Field source = this.getClass().getDeclaredField(field.getName());
            // 使字段都可以访问
            field.setAccessible(true);
            source.setAccessible(true);
            // 当前对象取出来的值
            field.set(vo,source.get(this));
        } catch (IllegalAccessException|NoSuchFieldException ignored) {}

    }
}
